package com.leozhang.app;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;

import java.net.URI;
import java.net.URL;
import java.time.Duration;

public class App 
{
    public static void main( String[] args ) {
        System.out.println( "Hello World!" );
        String bucketName = "leozhang";
        String objectKey = "Snipaste_2025-01-22_18-12-45.png";
        String accessKey = "XPK6OHJU8WS1DQB26FCO";
        String secretKey = "zySmsGybcUwHuf8S2NjQjDoBBbMpoYDZjClnAv8Q";
        String endpoint = "http://192.168.50.46:7480"; // Ceph RGW 端点
        int expireSeconds = 30; // 过期时间（秒）

        // 生成预签名 URL
        URL presignedUrl = generatePresignedUrl(bucketName, objectKey, accessKey, secretKey, endpoint, expireSeconds);
        System.out.println("预签名 URL: " + presignedUrl);
    }

    public static URL generatePresignedUrl(String bucket, String objectKey, String accessKey, String secretKey, String endpoint, int expireSeconds) {
        try (S3Presigner presigner = S3Presigner.builder()
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
                .endpointOverride(URI.create(endpoint)) // 指定 Ceph RGW 端点
                .region(Region.US_EAST_1)  // Ceph 兼容 AWS API，但区域无关
                .build()) {

            // 构造预签名请求
            GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
                    .signatureDuration(Duration.ofSeconds(expireSeconds)) // 过期时间
                    .getObjectRequest(req -> req.bucket(bucket).key(objectKey))
                    .build();

            // 生成预签名 URL
            PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(presignRequest);
            return presignedRequest.url();
        }
    }
}
